import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

// react-redux 不能同时调用多个dispatch, 所以需要使用@reduxjs/toolkit 的 createAsyncThunk
export const fetchHomeMultidataAction = createAsyncThunk(
  "fecth/homemultidata",
  async (extraInfo, { dispatch, getState }) => {
    /**
     extraInfo: 传递给dispatch的第二个参数
     dispatch: dispatch函数
     getState: 获取当前store中的状态
     */
    // 1.发送网络请求, 获取数据
    const res = await axios.get("http://123.207.32.32:8000/home/multidata")

    const banners = res.data.data.banner.list
    const recommends = res.data.data.recommend.list

    // 2.取出数据, 并且在此处直接dispatch操作(可以不做)
    dispatch(changeBanners(banners))
    dispatch(changeRecommends(recommends))

    // 3.返回结果, 那么action状态会变成fulfilled状态
    return res.data
  }
)

const homeSlice = createSlice({
  name: 'home',
  initialState: {
    banners: [],
    recommends: []
  },
  reducers: {
    changeBanners(state, { payload }) {
      state.banners = payload
    },
    changeRecommends(state, { payload }) {
      state.recommends = payload
    }
  },
  /** extraReducers的第一种写法 */
  // extraReducers: {
  //   [fetchHomeMultidataAction.pending](state, action) {
  //     console.log("pending")
  //   },
  //   [fetchHomeMultidataAction.fulfilled](state, { payload }) {
  //     console.log("fulfilled")
  //     state.banners = payload.data.banner.list
  //     state.recommends = payload.data.recommend.list
  //   },
  //   [fetchHomeMultidataAction.rejected](state, action) {
  //     console.log("rejected")
  //   }
  // }
  /** extraReducers的第二种写法 */
  extraReducers: (builder) => {
    // builder.addCase(fetchHomeMultidataAction.pending, (state, action) => {
    //   console.log("pending")
    // }).addCase(fetchHomeMultidataAction.fulfilled, (state, { payload }) => {
    //   console.log("fulfilled")
    //   state.banners = payload.data.banner.list
    //   state.recommends = payload.data.recommend.list
    // })
  }
})

export const { changeBanners, changeRecommends } = homeSlice.actions
export default homeSlice.reducer